<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div class="center_f" v-show="isShow">
            <!-- 搜索 -->
            <div class="box_si">
              <el-input
                placeholder="请输入姓名"
                v-model="input"
                @keyup.enter.native="searchBox()"
                clearable>
              </el-input>
            </div>
<!--             日期-->
            <div class="block">
              <el-date-picker
                v-model="userDate"
                type="daterange"
                align="right"
                unlink-panels
                range-separator=":"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <el-select v-model="value" clearable placeholder="状态" style="width: 100px;">
              <el-option
                v-for="(item) in options"
                :key="item.value"
                :label="item.label"
                :change="one()"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button type="success" icon="el-icon-search" size="small" class="box_ss" @click="searchBox()">搜索</el-button>
            <el-button type="warning" icon="el-icon-refresh" size="small" @click="resetForm()">重置</el-button>
          </div>
          <!--          增删改-->
          <div class="list_box_c">
              <span class="list_box_left">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addMembers()">新增</el-button>
                <el-button type="danger" disabled size="small" icon="el-icon-delete">删除</el-button>
                <el-button type="warning" size="small" icon="el-icon-download">导出</el-button>
              </span>
            <div class="list_box_right">
              <el-button icon="el-icon-search" size="small" @click="changeIsShow()"></el-button>
              <el-button icon="el-icon-refresh" size="small" @click="refresh()"></el-button>
            </div>
          </div>
          <!--          新增用户-->
          <el-dialog title="新增用户" :visible.sync="isAddMembers" width="30%" style="font-weight: bold">
            <el-form :model="addForms">
              <el-form :model="addForms" :rules="rules" ref="addForms" class="demo-ruleForm">
                <el-form-item label="姓名" prop="user_name">
                  <el-input v-model="addForms.user_name"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="addForms.phone"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                  <el-input v-model="addForms.email"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role_id">
                  <el-select v-model="addForms.role_id" placeholder="请输入">
                    <el-option label="超级管理员" value="0"></el-option>
                    <el-option label="普通用户" value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-form-item label="性别">
                <el-radio-group v-model="addForms.gendersex">
                  <el-radio :label="1" value="男">男</el-radio>
                  <el-radio :label="2" value="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog()">取 消</el-button>
              <el-button type="primary" @click="sumbitAddRow()">确 定</el-button>
            </span>
          </el-dialog>
<!--          编辑用户-->
          <el-dialog title="编辑用户" :visible.sync="centerDialogVisible" width="30%" style="font-weight: bold">
            <el-form :model="editForm">
              <el-form :model="editForm" :rules="rules" ref="addForms" class="demo-ruleForm">
                <el-form-item label="姓名" prop="user_name">
                  <el-input v-model="editForm.user_name"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="editForm.phone"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                  <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role_id">
                  <el-select v-model="editForm.role_id" placeholder="请输入">
                    <el-option label="超级管理员" value="0"></el-option>
                    <el-option label="普通用户" value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-form-item label="性别">
                <el-radio-group v-model="editForm.gendersex">
                  <el-radio :label="1" value="男">男</el-radio>
                  <el-radio :label="2" value="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog()">取 消</el-button>
              <el-button type="primary" @click="sumbitEditRow()">确 定</el-button>
            </span>
          </el-dialog>
          <div>
            <el-table
              ref="multipleTable"
              tooltip-effect="dark"
              style="width: 100%"
              :data = "pics"
              :model="addForms">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                label="日期"
                prop="create_time">
              </el-table-column>
              <el-table-column
                prop="user_name"
                label="姓名">
              </el-table-column>
              <el-table-column
                prop="phone"
                label="电话">
              </el-table-column>
              <el-table-column
                prop="email"
                label="邮箱">
              </el-table-column>
              <el-table-column
                prop="gendersex"
                label="性别"
                :formatter="formatPrivilegeType">
              </el-table-column>
              <el-table-column
                prop="status"
                label="状态">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.status"
                    :active-value="1"
                    :inactive-value="0"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="changeSwitch(scope.row.status,scope.row.user_id)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="operate"
                label="操作"
                width="150px">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" circle @click="modifyData(scope.$index, scope.row)"></el-button>
                  <el-button class="btn_x" type="text" icon="el-icon-delete" @click="removeUser (scope.row.user_id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--分页组件-->
            <pagination
              :total="totalCount"
              :pageNum="pageNum"
              :pageSize="pageSize"
              @pageChange="pageChange"
            />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import pagination from '../../../pagination/pagination'
  export default{
    inject: ['reload'],
    components: { pagination },
    data () {
      var validatorPhone = function (rule, value, callback) {
        if (value === '') {
          // callback(new Error('手机号不能为空'))
        } else if (!/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
          .test(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        msg: 'Welcome to Your Vue.js App',
        centerDialogVisible: false,
        isAddMembers: false,
        type: 3,
        // 修改
        editForm: {},
        pics: [],
        // 新增
        addForms: {},
        rules: {
          user_name: [
            {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}// 名字验证
          ],
          phone: [
            { required: true, trigger: 'blur', validator: validatorPhone }// 这里需要用到全局变量
          ],
          email: [
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }// 邮箱的验证
          ]
        },
        input: '',
        // 当前页码
        pageNum: 0,
        // 默认每页数据量
        pageSize: 5,
        totalCount: 0,
        // 搜索框显示或隐藏
        isShow: true,
        value3: true,
        istrue: '',
        isvalidate: '',
        sysUser: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        userDate: '',
        // 状态
        options: [{
          value: '1',
          label: '激活'
        }, {
          value: '0',
          label: '锁定'
        }],
        value: ''
      }
    },
    mounted: function () {
      this.searchBox()
      // const将变量声明为常量
      const that = this
      // 在窗口调整大小时发生
      window.onresize = function temp () {
        that.height = document.documentElement.clientHeight - 180 + 'px;'
      }
    },
    /**
     * @author hpx
     * @date 2021/9/24 8:58
     * 搜索名称按回车键
     */
    created () {
      const that = this
      document.addEventListener('keydown', that.searchBox())
    },
    methods: {
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 状态
       */
      changeSwitch(status, id) {
        this.$axios.post('/updateStatus', {
          user_id: id,
          status: status
          // 调用后台修改接口
        }).then(resp => {
          if (resp && resp.status === 200) {
            status = !status
          }
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 分页
       */
      pageChange(page) {
        this.pageSize = page.pageSize
        this.pageNum = page.currentPage
        this.searchBox()// 查询列表方法
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 查询，搜索框
       */
      searchBox() {
        // 判断搜索框，日期框，状态为空时，返回空字符串
        if (this.input == null) {
          return this.input == ""
        }
        if (this.userDate == "" || this.userDate == null) {
          this.userDate = ["",""]
        }
        if (this.value == null) {
          return this.value == ""
        }
        this.$axios.get('/searchUser', {
          params: {
            user_name: this.input,
            status: this.value,
            begindate: this.userDate[0],
            enddate: this.userDate[1],
            pageSize: this.pageSize,
            pageNum: this.pageNum
          }
        }).then(resp => {
          this.pics = resp.data.pagelist
          this.totalCount = resp.data.totalsize
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 重置搜索框，日期，下拉框
       */
      resetForm: function () {
        this.input = ''
        this.value = ''
        this.userDate = ''
        this.searchBox()
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 点击状态时触发
       */
      one() {
        if (this.value === '1') {
          this.type = 1
        } else if (this.value === '0') {
          this.type = 0
        }
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 性别转换为男女
       */
      formatPrivilegeType: function (row) {
        if (row.gendersex == '1') {
          return '男'
        } else if (row.gendersex == '2') {
          return '女'
        } else {
          return ''
        }
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 新增表格数据
       */
      addMembers() {
        this.isAddMembers = true
        this.addForms = {} // 再次点击新增时处于清空状态
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 保存并提交新增数据
       */
      sumbitAddRow() {
        if (this.addForms.user_name == '' || this.addForms.phone =='' || this.addForms.email == '' || this.addForms.role_id =='' || this.addForms.gendersex =='') {
          this.$confirm('请输入完整内容?', '提示', {
            type: 'warning'
          })
        } else {
          this.$axios
            .post('/addUser', this.addForms).then(resp => {
            this.istrue = resp.data
            if (this.istrue == '0') {
              this.$confirm('数据格式不规范?', '提示', {
                type: 'warning'
              })
            } else if (this.istrue == '1') {
              this.isAddMembers = false
              // location.reload()
            }
          })
        }
        setTimeout(() => {
          this.searchBox()
        }, 200)
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 关闭弹框
       */
      closeDialog() {
        this.centerDialogVisible = false
        this.isAddMembers = false
        this.reload() // 刷新页面
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 点击编辑时弹框打开
       */
      modifyData(index, row) {
        this.centerDialogVisible = true
        this.editForm = Object.assign({}, row) // 重置对象
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 保存并提交修改数据
       */
      sumbitEditRow() {
        if (this.editForm.user_name == '' || this.editForm.phone =='' || this.editForm.email == '' || this.editForm.role_id =='' || this.editForm.gendersex =='') {
          this.$confirm('请输入完整内容?', '提示', {
            type: 'warning'
          })
        }else {
          this.$axios
            .post('/updateUser', this.editForm).then(resp => {
            this.sysUser = resp.data.sysUser
            this.isvalidate = resp.data.isvalidate
            if (this.isvalidate == '0') {
              this.$confirm('数据格式不规范?', '提示', {
                type: 'warning'
              })
              // location.reload()
            } else if (this.isvalidate == '1') {
              this.centerDialogVisible = false
            }
          })
          setTimeout(() => {
            this.searchBox()
          }, 200)
        }
      },
      /**
       * @author hpx
       * @date 2021/9/24 14:01
       * 删除数据
       */
      removeUser(id) {
        this.$confirm('此操作将永久删除该文件?', '提示', {
          type: 'warning'
        }).then(() => {
          this.$axios
            .post('/deleteUser', {
              user_id: id
            }).then(resp => {
            if (resp && resp.status === 200) {
              this.searchBox()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 搜索框显示隐藏
       */
      changeIsShow() {
        this.isShow = !this.isShow
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 刷新表格
       */
      refresh() {
        this.reload()
      }
    }
  }
</script>

<style scoped>
  .el-col-lg-20 {
    width: 100%;
  }
  .table-grid-content {
    border-radius: 4px;
    height: 50px;
    background: #ebeef5;
    padding: 10px;
  }
  form {
    display: flex;
    flex-wrap: wrap;
  }
  .el-form-item {
    margin: 10px 25px;
  }
  .btn_x{
    display: inline-block;
    width: 40px;
    height: 40px;
    background: #F56C6C;
    border-radius: 50%;
    margin-left: 10px;
    color: white;
  }
</style>
